﻿namespace WinRTClient.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using WinRTClient.Model;
    using WinRTClient.Views;

    using Windows.UI.Xaml.Controls;

    using dot_in.HTWKAidStation.Client;
    using dot_in.HTWKAidStation.Client.Timetable;

    using StyleMVVM.DependencyInjection;
    using StyleMVVM.ViewModel;

    public class TimetableViewModel : PageViewModel
    {
        private bool isBusy;

        public TimetableViewModel()
        {
            this.Days = new ObservableCollection<EventDay>();
        }

        public EventCommand ItemClickCommand
        {
            get
            {
                return
                    new EventCommand(
                        (sender, args, parameter) =>
                        this.Navigation.Navigate(
                            typeof(EventDetailView),
                            new SelectedEventNavigationArgs
                                {
                                    Events = this.FindCorrespondingDay((Event)((ItemClickEventArgs)args).ClickedItem),
                                    SelectedEvent = (Event)((ItemClickEventArgs)args).ClickedItem
                                }));
            }
        }

        public ObservableCollection<EventDay> Days { get; set; }

        public bool IsBusy
        {
            get
            {
                return isBusy;
            }

            set
            {
                this.isBusy = value;
                this.OnPropertyChanged();
            }
        }

        protected override void OnNavigatedTo(object sender, StyleMVVM.View.StyleNavigationEventArgs e)
        {
            this.LoadData((TutorialGroup)((object[])e.Parameter)[0], (Week)((object[])e.Parameter)[1]);
            base.OnNavigatedTo(sender, e);
        }

        private ObservableCollection<Event> FindCorrespondingDay(Event clickedItem)
        {
            return this.Days.Where(day => day.Events.Contains(clickedItem)).Select(day => day.Events).FirstOrDefault();
        }

        private async void LoadData(TutorialGroup tutorialGroup, Week week)
        {
            this.IsBusy = true;
            List<EventDay> days = await Core.ParseTimetable(tutorialGroup.ID, week.ID);
            foreach (EventDay eventDay in days)
            {
                this.Days.Add(eventDay);
            }

            this.IsBusy = false;
        }
    }
}
